//
//  TSRequestData.swift
//  TopStock
//
//  Created by dyd on 2017/8/12.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit

class TSRequestData: NSObject {
    
//    test.com.cloudshadow.platform.topstock
//    生产就
//    com.cloudshadow.platform.topstock
//    ？
    
    //获取极光注册成功以后得到标识设备的registrationID
    public func getRegistrationID() ->String?
    {
        let registrationID = UserDefaults.standard.object(forKey: KRegistrationID) as? String
        if registrationID != nil{
            return registrationID
        }else{
            return nil
        }
    }
    
    //获取微信的Open ID
    public func getOpenID() -> String?
    {
        let openID = UserDefaults.standard.object(forKey: KOpenID) as? String
        if openID != nil{
            return openID
        }else{
            return nil
        }
    }
    
    //获取Access Token
    public func getAccessToken() ->String?{
        let accessToken = UserDefaults.standard.object(forKey: KAccessToken) as? String
        print("accessToken ==>:\(String(describing: accessToken))")
        if accessToken != nil{
            return accessToken
        }else{
            return nil
        }
    }
    
    /**************************************
     http://118.178.254.31:8060/usercenter  用户中心
     ***************************************/
    let usercenterURL = "http://118.178.254.31:8060/usercenter"//用户中心
    //用户注册verify_code
    public func register(phoneNumber:String,
                         password:String,
                         verifyCcode:String,
                         inviteCode:String?,
                         isPhoneRegister:Bool) ->NSDictionary?
    {
        let urlStr = usercenterURL + "/register"
        let url:NSURL = NSURL(string: urlStr)!
        var param:NSString
        if isPhoneRegister{
             param = NSString(format:"login_account=%@&verify_code=%@&password=%@&invite_code=%@",phoneNumber,verifyCcode,password,inviteCode!)
        }else{
            let openID = getOpenID()
            let registrationID = getRegistrationID()
            print("openID ==>:\(String(describing: openID))")
            print("registrationID ==>:\(String(describing: registrationID))")
            param = NSString(format:"login_account=%@&verify_code=%@&password=%@&invite_code=%@&open_id=%@&registration_id=%@",phoneNumber,verifyCcode,password,inviteCode!,openID!,registrationID!)
        }
        print("param ==>:\(param)")
        let restDic = postRequest(url: url, param: param) as? NSDictionary
        print("restDic ==>:\(String(describing: restDic))")
        return restDic
    }
    
    //微信登陆
    func wechatLogin() ->NSDictionary?
    {
        let open_id = getOpenID()
        let registration_id = getRegistrationID()
        print("open_id ==>:\(open_id)")
        print("registration_id ==>:\(registration_id)")
        let urlStr = usercenterURL + "/wechatLogin"
        let url:NSURL = NSURL(string: urlStr)!
        let jsonDic = ["open_id":open_id,"registration_id":registration_id]
        return postBodyRequest(url: url, jsonDic: jsonDic) as? NSDictionary
    }

    
    //用户登陆
    public func login(phoneNumber:String,
                      password:String) ->NSDictionary?
    {
        let urlStr = usercenterURL + "/login"
        let url:NSURL = NSURL(string: urlStr)!
        let registrationid = getRegistrationID()
        let jsonDic = ["login_account":phoneNumber,"password":password,"registration_id":registrationid]
        return postBodyRequest(url: url, jsonDic: jsonDic) as? NSDictionary
    }
    
//    POST /usercenter/logout
    //退出登陆
    public func logout() ->NSDictionary?
    {
        let urlStr = usercenterURL + "/logout"
        let url:NSURL = NSURL(string: urlStr)!
        let accessToken = getAccessToken()
        let jsonDic = ["access_token":accessToken]
        return postBodyRequest(url: url, jsonDic: jsonDic) as? NSDictionary
    }

    
//    //输入短信验证码点击下一步
//    public func changePhone(phoneNumber:String,
//                            code:String) -> NSDictionary
//    {
//        let urlStr = usercenterURL + "/changePhone"
//        let url:NSURL = NSURL(string: urlStr)!
//        let accessToken = getAccessToken()
//        let jsonDic = ["access_token":accessToken,"code":code,"phone":phoneNumber]
//        return postBodyRequest(url: url, jsonDic: jsonDic) as! NSDictionary
//    }
    
    //获取用户个人信息详情
    public func getUserInfo() ->NSDictionary?{
        let urlStr = usercenterURL + "/getUserInfo"
        let url:NSURL = NSURL(string: urlStr)!
        let accessToken = getAccessToken()
        let jsonDic = ["access_token":accessToken]
        return postBodyRequest(url: url, jsonDic: jsonDic) as? NSDictionary
    }
    
    
//     /usercenter/addVideoViewingTime
    //增加视频观看时间
    public func addVideoViewingTime(videoTime:Double)
    {
        let urlStr = usercenterURL + "/addVideoViewingTime"
        let url:NSURL = NSURL(string: urlStr)!
        let accessToken = getAccessToken()
        let jsonDic = ["access_token":accessToken!,"video_viewing_time":videoTime] as [String : Any]
        let dic = postBodyRequest(url: url, jsonDic: jsonDic) as? NSDictionary
    }
    
    
    
    /**************************************
     http://118.178.254.31:8060/verifycode
    ***************************************/
    let verifycodeURL = "http://118.178.254.31:8060/verifycode"//验证码中心
    //获取获取验证码
    public func getCode(phoneNumber:String,verify_type:Int) ->NSDictionary
    {
        let urlStr = verifycodeURL + "/getCode"
        let url:NSURL = NSURL(string: urlStr)!
        let accessToken = getAccessToken()
        let jsonDic = ["access_token":accessToken,"phone":phoneNumber,"verify_type":verify_type] as [String : Any?]
        return postBodyRequest(url: url, jsonDic: jsonDic) as! NSDictionary
    }
    
    //检验验证码
    public func checkVerifyCode(phoneNumber:String,verifyCcode:String,verify_type:Int) ->NSDictionary
    {
        //verify_type
        let urlStr = usercenterURL + "/checkVerifyCode"
        let url:NSURL = NSURL(string: urlStr)!
        let jsonDic = ["phone":phoneNumber,"verify_code":verifyCcode,"verify_type":verify_type] as [String : Any?]
        return postBodyRequest(url: url, jsonDic: jsonDic) as! NSDictionary
    }
    
    //重置密码
    public func resetPwd(password:String?,resetPwdToken:String?) ->NSDictionary
    {
        let urlStr = usercenterURL + "/resetPwd"
        let url:NSURL = NSURL(string: urlStr)!
        let accessToken = getAccessToken()
        let jsonDic = ["access_token":accessToken,"password":password,"reset_pwd_token":resetPwdToken]
        return postBodyRequest(url: url, jsonDic: jsonDic) as! NSDictionary
    }
    
    /**************************************
     http://118.178.254.31:8060/informationcenter  资讯中心
     **************************************/
    private let informationcenterURL = "http://118.178.254.31:8060/informationcenter"//咨询详情
    func informationDetail(id:String?) ->NSDictionary
    {
        let urlStr = informationcenterURL + "/informationDetail"
        let url:NSURL = NSURL(string: urlStr)!
        let accessToken = getAccessToken()
        let jsonDic = ["id":id,"access_token":accessToken]
        return postBodyRequest(url: url, jsonDic: jsonDic) as! NSDictionary
    }
    
    //日历中心   /calendar/getCalendars
    public func getCalendars(apply_time:String) ->NSDictionary?
    {
        let param = NSString(format:"access_token=%@&pageSize=10&pageNo=1&sort=create_time&apply_time=%@",getAccessToken()!,apply_time)
        let url:NSURL = NSURL(string:"http://118.178.254.31:8060/calendar/getCalendars")!
        let restDic = postRequest(url: url, param: param) as? NSDictionary
        return restDic!
    }
    
    
    //数据请求 access_Token 设置在body里面
    func postBodyRequest(url:NSURL,jsonDic:Any) ->Any?
    {
        let jsonData = try! JSONSerialization.data(withJSONObject: jsonDic, options: [])
        var request:URLRequest = URLRequest(url: url as URL)
        request.timeoutInterval = 5.0
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        var jsonDic:NSDictionary?
        //发送请求
        var response:URLResponse?
        let receivedData =  try? NSURLConnection.sendSynchronousRequest(request, returning: &response)
        if receivedData != nil {
            jsonDic = try? JSONSerialization.jsonObject(with: receivedData!, options: .mutableLeaves) as! NSDictionary
        }
        return jsonDic
    }
    
    //上传头像图片
    func upload(fileData:NSData!,fileName:NSString)
    {
        let uploadUrl = NSURL(string: "http://118.178.254.31:8060/filecenter/upload")
        var request:URLRequest = URLRequest(url: uploadUrl! as URL)
        request.timeoutInterval = 5.0
        request.httpMethod = "POST"
        let boundary:String="******"
        
        let contentType:String="multipart/form-data;boundary="+boundary
        
        request.addValue(contentType, forHTTPHeaderField:"Content-Type")
        
        let body=NSMutableData()
        //在表单中插入要上传的数据
        body.append(NSString(format: "--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!);
        body.append(NSString(format: "Content-Disposition:form-data;name=\"userid\"\r\n\r\n").data(using: String.Encoding.utf8.rawValue)!)
        
        body.append("\r\n".data(using: String.Encoding.utf8)!)
        //在表单中写入要上传的图片
        body.append(NSString(format:"--\(boundary)\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
        body.append(NSString(format:"Content-Disposition:form-data;name=\"image\";filename=\(fileName)\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
        body.append("Content-Type:image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
        body.append(fileData! as Data)
        
        body.append(NSString(format:"\r\n--\(boundary)--\r\n" as NSString).data(using: String.Encoding.utf8.rawValue)!)
        //设置post的请求体
        request.httpBody = body as Data
        var jsonDic:NSDictionary?
        //发送请求
//        var response:URLResponse?
//        let receivedData =  try? NSURLConnection.sendSynchronousRequest(request, returning: &response)
//        if receivedData != nil {
//            jsonDic = try? JSONSerialization.jsonObject(with: receivedData!, options: .mutableLeaves) as! NSDictionary
//        }
        let que=OperationQueue()
        
        NSURLConnection.sendAsynchronousRequest(request, queue: que, completionHandler: {
            (response, data, error) ->Void in
            if (error != nil){
                print(error!)
            }else{
                jsonDic = try? JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSDictionary
                if jsonDic != nil
                {
                    NotificationCenter.default.post(name:NSNotification.Name(rawValue: "refreshPicture"), object: nil, userInfo: ["result":jsonDic!])
                    print("receivedData ==>:\(String(describing: jsonDic))")
                }
            }
        })
    }
    
//    /usercenter/save
    func save()
    {
        
    }
 
//
    //数据请求
    func postRequest(url:NSURL,param:NSString) -> Any?{
        //创建请求对象
        var request:URLRequest = URLRequest(url: url as URL) //默认为get请求
        request.timeoutInterval = 5.0 //设置请求超时为5秒
        request.httpMethod = "POST"  //设置请求方法
        //把拼接后的字符串转换为data，设置请求体
        request.httpBody = param.data(using: String.Encoding.utf8.rawValue)
        var jsonDic:NSDictionary?
        //发送请求
        var response:URLResponse?
        let receivedData =  try? NSURLConnection.sendSynchronousRequest(request, returning: &response)
        if receivedData != nil {
            jsonDic = try? JSONSerialization.jsonObject(with: receivedData!, options: .mutableLeaves) as! NSDictionary
        }
        return jsonDic
    }

}
